package com.lixl.collection;

import java.util.Iterator;

public class MyMap<K, V> {

	private int actualSize = 0;// 初始化实际数组大小

	@SuppressWarnings("unchecked")
	Entity[] entitys = new MyMap.Entity[10];

	/**
	 * 存值
	 * 
	 * @param key
	 * @param value
	 */
	public void put(K key, V value) {
		resize();

		for (int i = 0; i < actualSize; i++) {
			Entity obj = entitys[i];
			if (obj != null && obj.getKey().equals(key)) {
				obj.setValue(value);
				return;
			}
		}

		entitys[actualSize] = new Entity(key, value);
		actualSize++;
	}

	/**
	 * 取值
	 * 
	 * @param key
	 * @return V
	 */
	public V get(K key) {
		V value = null;
		for (int i = 0; i < actualSize; i++) {
			Entity obj = entitys[i];
			if (obj != null && obj.getKey().equals(key)) {
				value = obj.getValue();
				break;
			}
		}
		return value;
	}

	// 数组扩容
	@SuppressWarnings("unchecked")
	private void resize() {
		if (actualSize >= entitys.length) {
			int size = actualSize * 2;
			Entity[] newEntitys = new MyMap.Entity[size];
			System.arraycopy(entitys, 0, newEntitys, 0, entitys.length);
			entitys = newEntitys;
			newEntitys = null;
		}
	}

	/**
	 * 获取数据容量
	 * 
	 * @return int
	 */
	public int size() {
		return actualSize;
	}

	/**
	 * 遍历数据
	 * 
	 * @return Iterator<MyMap<K, V>.Entity>
	 */
	public Iterator<MyMap<K, V>.Entity> iterator() {
		return new Iterator<MyMap<K, V>.Entity>() {
			private int currentIndex = 0;

			@Override
			public boolean hasNext() {
				return currentIndex < actualSize;
			}

			@Override
			public MyMap<K, V>.Entity next() {
				return entitys[currentIndex++];
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException(
						"cannot remove items from an array");
			}
		};
	}

	class Entity {
		private K key;
		private V value;

		public Entity(K key, V value) {
			this.key = key;
			this.value = value;
		}

		public K getKey() {
			return key;
		}

		public V getValue() {
			return value;
		}

		private void setValue(V value) {
			this.value = value;
		}
	}

}
